// pages/ticket/ticket.js
const app = getApp() //获取应用实例
let request = require("../../utils/request.js")
let config = require('../../config/config.js')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    barHeight: wx.getMenuButtonBoundingClientRect().bottom,
    parkTicketList: [],
    discountTicketList: [],
    selectedTicketIndex: 1,
    activationDialog: false,
    selectedTicket: {},
    infoDialog: false,
    content: null,
    parkNameList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      selectedTicketIndex: options.state ? Number(options.state) : 1
    })
    //  获取卡券
    this.getCustParkTicket()
    //  获取用户的优惠券
    this.getCustDiscountTicket() 

    // // 接受消息
    wx.onSocketMessage(result => {
      console.log('激活：' + result.data);
      let text = result.data;
      if(text.indexOf('activate-ticket@') != -1){
        wx.showToast({
          title: '激活成功',
          duration: 2000,
          icon: 'none'
        })
        this.closeActivationDialog()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 切换卡券
   */
  switchTicket(e) {
    this.setData({ selectedTicketIndex: e.currentTarget.dataset.ticketIndex })
  },

  /**
   * 获取停车券
   */
  getCustParkTicket() {
    // this.setData({ selectedTicketIndex: 1 })
    request.http(
      '/customer/ticket/get-cust-park-ticket', 
      'GET',
      true
    ).then((res) => {
        console.log('卡券：', res)
        if (res.data.code == 200) {
          this.setData({ parkTicketList: res.data.data })

          //下面部分是不同的劵处理的图片显示。  后来需求改为不展示图片，没删除怕以后再改回
          
          let logoUrl = "";
          let parkImgUrls = [];
          let parkImgUrl = '';
          this.data.parkTicketList.map((r,ind)=>{
            if(r.fromType == 2){
              if(r.parkImgUrl){
                let url = r.parkImgUrl.split(',')[0];
                let index = url.lastIndexOf(".")
                let name = url.substr(0, index)
                let ext = url.substr(index+1)
                parkImgUrl = name + '@_@350.' + ext
              }else{
                parkImgUrl = 'https://mis.lmtc.zmzncs.com/file/WeChat/ticket-icon.png'
              }
              parkImgUrls.push(parkImgUrl)
              logoUrl = "parkTicketList["+ind+"].logo";
              this.setData({
                [logoUrl] : parkImgUrl
              })
            }
          })
        }
      })
  },

    /**
   * 获取用户的优惠券
   */
  getCustDiscountTicket() {
    // this.setData({ selectedTicketIndex: 2 })
    request.http(
      '/customer/ticket/get-cust-discount-ticket', 
      'GET'
    ).then((res) => {
      console.log('卡券：', res)
      if (res.data.code == 200) {
        this.setData({ discountTicketList: res.data.data })
      }
    })
  },

    /**
   * 历史卡券
   */
  history(){
    if(this.data.selectedTicketIndex == 1){
      wx.navigateTo({  url: '/pages/cust-ticket/cust-history-park-ticket/custHistoryParkTicket' })
    } else {
      wx.navigateTo({  url: '../parkingCoupon/parkingCoupon' })
    }
  },

  /**
   * 显示激活码弹窗
   */
  showActivationDialog(e) {
    let parkTicket = e.currentTarget.dataset.parkTicket
    request.http(
      '/customer/ticket/park-ticket-qr-code', 
      'GET',
      { id: e.currentTarget.dataset.parkTicket.id }
    ).then((res) => {
      this.setData({
        selectedTicket: {
          id: parkTicket.id,
          shopName: parkTicket.shopName,
          ticketCode: parkTicket.ticketCode,
          validityDays: parkTicket.validityDays,
          parkingDuration: parkTicket.parkingDuration,
          activationQrCode: res.data
        },
        activationDialog: true 
      })
    })
  },
  
  /**
   * 显示详情
   */
  showInfo(e){
    console.log(e)
    this.setData({ content: e.currentTarget.dataset.content, infoDialog: true })
  },

    /**
   * 展示适用停车场
   */
  showParks(e){
    let parkTicket = e.currentTarget.dataset.parkTicket;
    // grantType   发放类型，1：平台发放；2：活动发放；3：自主领取
    // fromType=1 商户  fromType=2 平台
    console.log(parkTicket);
    // if (parkTicket.fromType ==1) {
    //   console.log('商户发放');
    //   console.log(parkTicket.shopName);
    //   let parkNames = parkTicket.shopName;
    //   this.setData({ content: parkNames, infoDialog: true });
    // }
    // if(parkTicket.fromType ==2 ) {
    //   console.log(parkTicket.fromType);
    //   console.log('平台发放');
    //   let parkNames = '【平台所有停车场】';
    //   this.setData({ content: parkNames, infoDialog: true });
    //   return false
    // }
    // console.log(parkTicket);
    // console.log(parkTicket.fromType);

    // grantType发放类型
    // console.log(parkTicket.grantType);
    // if(parkTicket.grantType >= 1){
    //   let parkNames = '【平台所有停车场】';
    //   this.setData({ content: parkNames, infoDialog: true });
    //   return false
    // }

    request.http(
      '/shop/park-ticket-set/get-for-parks', 
      'GET', 
      { custTicketId: parkTicket.id },
      1,
      false
    ).then(res => {
      if(res.data.code == 200 ){
        console.log(res)
        if ( res.data.data ) {

          // for ( var i = 0; i<parkList.length; i++ ) {
          //   console.log(parkList[i].parkImgUrl);
          //   if (parkList[i].parkImgUrl == '') {
          //     parkList[i].parkImgUrl = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017bcb58b4db5fa801219c7719b5ff.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631772791&t=f97c88d0443ed9fe68c2ee2a27ee5096';
          //   }
          // }
        }
        // if ( res.data.data.length == 1 ) {
        //   console.log('商户停车场');
        //   let parkNames = res.data.data[0].parkName;
        //   this.setData({ content: parkNames, infoDialog: true });
        // }
        // if ( res.data.data.length >= 10) {
        //   console.log(res.data.data);
        //   console.log('平台所有停车场');
        //   let parkNames = '【平台所有停车场】';
        //   this.setData({ content: parkNames, infoDialog: true });
        // }
        let parkNames = ''
        res.data.data.forEach((park)=> {
          parkNames += '【' + park.parkName + '】'
        })
        this.setData({ content: parkNames, infoDialog: true })
      }
    })
  },

  /**
   * 关闭激活码弹窗
   */
  closeActivationDialog(){
    console.log('关闭弹窗')
    request.http(
      '/customer/ticket/get-by-id', 
      'GET',
      { id: this.data.selectedTicket.id }
    ).then((res) => {
      console.log('status:', res.data.data.status)
      if(res.data.code == 200){
        this.getCustParkTicket()
      }
      this.data.parkTicketList.forEach((parkTicket, index)=> {
        if(parkTicket.id == this.data.selectedTicket.id){
          let status = 'parkTicketList[' + index + '].status'
          this.setData({ [status]: res.data.data.status })
        }
      })
    })
    
    this.setData({ activationDialog: false })
  },

    /**
   * 关闭弹窗
   */
  closeDialog(e) {
    this.setData({ infoDialog: false })
  },

    /**
   * 返回
   */
  back(){
    wx.navigateBack({ delta: 1 })
  },
  //拨打商户电话
  callPhone(e){
    console.log(e)
    if(e.target.dataset.phone){
      wx.makePhoneCall({
        phoneNumber: e.target.dataset.phone, //仅为示例，并非真实的电话号码
        fail: function(res) {
        },
      })
    }else{
      wx.makePhoneCall({
        phoneNumber: '17692120322', //仅为示例，平台劵没有 商户，暂时写成 客服电话
        fail: function(res) {
        },
      })
    }
  },
})